<template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <!--  <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                        placeholder="问答人id"
                        v-model="listQuery.entity.question.userId">
              </el-input>-->
            <!--   <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                         placeholder="商品id"
                         v-model="listQuery.entity.question.goodsId">
               </el-input>-->
            <el-select filterable @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                       v-model="listQuery.entity.question.goodsId"
                       placeholder="商品名">
                <el-option v-for="(item,index) in  goodsList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
            <!--<el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="问答人昵称"
                      v-model="listQuery.entity.question.userName">
            </el-input>-->
            <!--     <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                           placeholder="问题内容"
                           v-model="listQuery.entity.question.content">
                 </el-input>-->
            <!-- <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                       placeholder="头像"
                       v-model="listQuery.entity.question.avatar">
             </el-input>-->
            <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                       v-model="listQuery.entity.question.status"
                       placeholder="状态">
                <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
                </el-option>
            </el-select>
            <el-date-picker
                    @change='handleFilter'
                    value-format="yyyy-MM-dd HH:mm:ss"
                    class="filter-item input"
                    v-model="listQuery.entity.question.times"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="问题时间开始日期"
                    end-placeholder="问题时间结束日期">
            </el-date-picker>

            <div style="display: inline-block">

                <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"
                           @click="handleFilter">查找
                </el-button>
                <!--                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"-->
                <!--                           v-if="canSave" icon="el-icon-edit">添加-->
                <!--                </el-button>-->
                <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                           @click="handleDownload">导出
                </el-button>
            </div>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
                  style="width: 100%;">
            <yf-table-column align="center" label="ID">
                <template slot-scope="scope">
                    <span>{{scope.row.question.id}}</span>
                </template>
            </yf-table-column>
            <!-- <yf-table-column align="center" label="问答人编号">
                 <template slot-scope="scope">
                     <span v-if="scope.row.question">{{scope.row.userCode}}</span>
                 </template>
             </yf-table-column>-->
            <yf-table-column align="center" label="店铺">
                <template slot-scope="scope">
                    <span v-if="scope.row.question">{{scope.row.question.shop?scope.row.question.shop.name:'社集优选自营店'}}</span>
                </template>
            </yf-table-column>
            <yf-table-column align="center" label="商品名">
                <template slot-scope="scope">
                    <span v-if="scope.row.question">{{scope.row.goodsName}}</span>
                </template>
            </yf-table-column>
            <yf-table-column align="center" label="问答人昵称">
                <template slot-scope="scope">
                    <span v-if="scope.row.question">{{scope.row.question.userName}}</span>
                </template>
            </yf-table-column>
            <yf-table-column align="center" label="问题内容">
                <template slot-scope="scope">
                    <span v-if="scope.row.question">{{scope.row.question.content}}</span>
                </template>
            </yf-table-column>
            <!-- <yf-table-column align="center" label="头像">
                 <template slot-scope="scope">
                     <span v-if="scope.row.question">{{scope.row.question.avatar}}</span>
                 </template>
             </yf-table-column>-->
            <yf-table-column align="center" label="状态">
                <template slot-scope="scope">
                                                <span v-if="scope.row.question">

                         <el-tag :type="tagTypes[scope.row.question.status]" v-if="scope.row.question.status!=null">     {{statusOptions[scope.row.question.status]}}</el-tag>

                        </span>
                </template>
            </yf-table-column>
            <yf-table-column align="center" label="是否已回答">
                <template slot-scope="scope">
                      <span v-if="scope.row.question">
                         <el-tag :type="tagTypes[scope.row.question.isAnswer]" v-if="scope.row.question.isAnswer!=null">
                             {{isAnswerOptions[scope.row.question.isAnswer]}}
                         </el-tag>
                       </span>
                </template>
            </yf-table-column>
            <yf-table-column v-if="!userId" align="center" label="回答是否有待审核">
                <template slot-scope="scope">
                      <span v-if="scope.row.question">
                         <el-tag :type="tagTypes[scope.row.question.isAnswerAudit]" v-if="scope.row.question.isAnswerAudit!=null">
                             {{isAnswerOptions[scope.row.question.isAnswerAudit]}}
                         </el-tag>
                       </span>
                </template>
            </yf-table-column>
            <yf-table-column align="center" label="问题时间" width="160">
                <template slot-scope="scope">
                    <span v-if="scope.row.question">{{parseTime(scope.row.question.time)}}</span>
                </template>
            </yf-table-column>

            <yf-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope)">编辑</el-button>
                    <el-button v-if="canSave" size="mini" type="danger"
                               @click="handleDelete(scope)">删除
                    </el-button>
                </template>
            </yf-table-column>

        </el-table>

        <div class="pagination-container" style="margin-top: 20px">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 450px; margin-left:50px;'>
                <!--<el-form-item label="问答人编号" prop="question.userId">
                    <el-input v-model="temp.question.userId"></el-input>
                </el-form-item>-->
                <el-form-item label="商品名称" prop="question.goodsId">
                    <el-input disabled v-model="temp.goodsName"></el-input>
                </el-form-item>
                <el-form-item label="问答人昵称" prop="question.userName">
                    <el-input disabled v-model="temp.question.userName"></el-input>
                </el-form-item>
                <el-form-item label="问题内容" prop="question.content">
                    <el-input disabled type="textarea" maxlength="40" v-model="temp.question.content"></el-input>
                </el-form-item>
                <el-form-item v-for="(item,index) in temp.question.list" :label="'回答内容'+(index+1)"
                              prop="question.content">
                    <div style="display: flex">
                        <el-input :disabled="item.status" style="width: 500px;margin-right: 5px" type="textarea" maxlength="40"
                                  v-model="item.content"></el-input>
                        <el-select :disabled="adminFlag" class="filter-item" v-model="item.status" placeholder="状态">
                            <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                       :value="index">
                            </el-option>
                        </el-select>
                    </div>
                    <el-input v-if="!item.status" :disabled="adminFlag" style="margin-top: 5px" placeholder="请输入未通过原因"  type="textarea" maxlength="100"
                              v-model="item.remark"></el-input>
                </el-form-item>
                <el-form-item v-if="answerSize < 3" :label="'回答内容'+answerIndex" prop="question.content">
                    <el-input type="textarea" maxlength="40" v-model="temp.answerContent"></el-input>
                </el-form-item>
                <el-form-item label="头像" prop="question.avatar">
                    <div class="block">
                        <el-avatar :size="50" :src="temp.question.avatar"></el-avatar>
                    </div>
                </el-form-item>
                <el-form-item label="状态" prop="question.status">
                    <el-select @change="selectQuestion" class="filter-item" v-model="temp.question.status" placeholder="状态">
                        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="!temp.question.status" label="未通过原因" prop="question.remark">
                    <el-input type="textarea" placeholder="请输入未通过原因" maxlength="40" v-model="temp.question.remark"></el-input>
                </el-form-item>
                <el-form-item label="问题时间" prop="question.time">
                    <el-date-picker disabled v-model="temp.question.time" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="问题时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item style="pointer-events:none" label="问题图" prop="question.img">
                    <el-upload
                            ref="imgUpload"
                            action="http://upload.qiniup.com"
                            :auto-upload="true"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :before-upload="handleUpload"
                            :file-list="imgList"
                            :on-success="(response, file, fileList)=>handleImgUploadSuccess(imgList,file)"
                            :data="qData"
                            :on-remove="(file, fileList)=>handleImgRemove(imgList,file)">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-dialog :visible.sync="dialogVisible" append-to-body>
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list, options, down, info, save, update, remove} from '@/api/question'
    import waves from '@/directive/waves' // 水波纹指令
    import {downExcel} from '@/utils/down.js'
    import {parseTime} from '@/utils'

    import {getToken, domain} from '@/api/qiniu'
    import {listToStrs, strsToList} from '@/utils/imgUtil'

    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                tableKey: 0,
                list: null,
                total: null,
                listLoading: true,
                time: null
                ,
                userId: null,
                adminFlag: false,
                answerIndex: '',
                answerSize: 0,
                goodsList: null,
                listQuery: {
                    page: 1,
                    limit: 20,
                    order: 'question.id desc',
                    entity: {
                        question:
                            {
                                id: null,
                                userId: null,
                                goodsId: null,
                                userName: null,
                                img: null,
                                content: null,
                                time: null,
                                status: null,
                                avatar: null,

                            }
                    }
                },
                statusOptions: [],
                isAnswerOptions: ["否",'是'],
                tagTypes: ['info', '', 'warning', 'danger', 'warning'],
                temp: {

                    question:
                        {
                            id: null,
                            userId: null,
                            goodsId: null,
                            userName: null,
                            img: null,
                            content: null,
                            time: null,
                            status: null,
                            remark: null,
                            isAnswerAudit: null,
                            isAnswer:null,
                            avatar: null
                        },
                    answerContent: null,
                    goodsName: null,
                }
                ,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                }
                ,
                // 存在图片
                dialogImageUrl: '',
                dialogVisible: false,
                imgList: [],
                rules:
                    {
                        'question.userId': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.remark': [
                            {
                                required: true,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ],
                        'question.goodsId': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.userName': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.img': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.content': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.time': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                        ,
                        'question.status': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'blur'
                            }
                        ]
                        ,
                        'question.avatar': [
                            {
                                required: false,
                                message: '必填字段',
                                trigger: 'change'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key: ''
                    }
            }
        },
        created() {
            this.getList()
            this.getOptions()
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            canSave() {
                return hasAuth(this.perms, 'question:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'question:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'question:update')
            },
            canList() {
                return hasAuth(this.perms, 'question:list')
            }
        },
        methods: {
            selectQuestion(index){
                if (index){
                    this.temp.question.remark = null
                }
            },
            parseTime(time) {
                if (!time) return ''
                return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
            },
            getList() {
                this.listLoading = true
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.goodsList = response.extra.goodsList
                    if (response.extra.userId) {
                        this.adminFlag = true
                    }
                    this.userId = response.extra.userId
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            getOptions() {
                options().then(res => {
                    this.statusOptions = res.data.statusOptions
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片
                this.initQiniu()

                // 存在图片字段转换图片地址显示
                this.initImgUrl()
            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
                this.initImgName()// 图片转换
            },
            resetTemp(row) {

                this.temp = {
                    question: {}
                }
                if (row) {
                    this.temp = Object.assign({}, row) // copy obj
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                })
            },
            // 显示将图片名封装成可以展示状态集合
            initImgUrl() {
                this.imgList = strsToList(this.temp.question.img, domain)
            },
            // 关闭显示窗口 重置图片地址 防止错乱
            resetImgUrl() {
                this.imgList = []
            },
            // 上传或者更新的时候从图片链接中获取图片名字
            initImgName() {
                this.temp.question.img = listToStrs(this.imgList)
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()

                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.question.id]
                const ids = [this.list[this.index].question.id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.answerSize = 0
                this.answerIndex =''
                this.beforeFormShow(scope.row)
                info(scope.row.question.id).then(res => {
                    this.temp = res.data
                    if (this.temp.question.list.length > 0) {
                        this.answerIndex = this.temp.question.list.length + 1
                        this.answerSize = this.temp.question.list.length
                    }
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.$nextTick(() => {
                        this.$refs['dataForm'].clearValidate()
                    })
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            update(this.temp).then(() => {
                                // this.list.splice(this.index, 1, this.temp)
                                this.getList()
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                // 存在图片
                this.resetImgUrl()
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                down(this.listQuery).then(res => {
                    downExcel(res)
                    this.downloadLoading = false
                    this.$notify({
                        title: '成功',
                        message: '下载成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            // formatJson(filterVal, jsonData) {
            //     return jsonData.map(v => filterVal.map(j => {
            //         return v[j]
            //     }
            // ))
            // },
            // 存在图片
            handleUpload(file) {
                this.qData.key = new Date().valueOf() + file.name
            },
            initQiniu() {
                // 获取七牛配置
                getToken().then(res => {
                    this.qData.token = res.data
                }).catch(error => {
                    console.log(error)
                })
            },
            handleImgUploadSuccess(imgList, file) {
                imgList.push({name: file.response.key, url: domain + file.response.key})
            },
            handleImgRemove(imgList, file) {
                for (var fn of imgList) {
                    if (fn.name === file.name) {
                        imgList.splice(imgList.indexOf(fn), 1)
                    }
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            }
        }
    }
</script>
